<?php


try {
	if( $_POST['use_ftp'] ) {
		$writer = new writer_ftp( $_POST['ftp_host'], $_POST['ftp_user'], $_POST['ftp_pass'], $_POST['ftp_dir'] );
	} else {
		$writer = new writer_fs();
	}

	// Test connections
	$writer->dir('db/');
	if( !$db = new sqlite_connection('db/system.sqlite'))
		throw new Exception('Database connection failed!');

	// Install basic database
	$db->query("CREATE TABLE IF NOT EXISTS `update_server` (
		`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
		`name` varchar(100) NOT NULL,
		`url` text NOT NULL,
		`update_date` int(10) unsigned NOT NULL,
		`update_by` int(10) unsigned NOT NULL,
		`create_date` int(10) unsigned NOT NULL,
		`create_by` int(10) unsigned NOT NULL,
		PRIMARY KEY (`id`)
	) ENGINE=InnoDB  DEFAULT CHARSET=utf8;");

	$db->query("CREATE TABLE IF NOT EXISTS `update_package` (
		`id` varchar(200) NOT NULL,
		`source` int(10) unsigned DEFAULT NULL,
		`version` int(10) unsigned NOT NULL,
		`update_date` int(10) unsigned NOT NULL,
		`update_by` int(10) unsigned NOT NULL,
		`create_date` int(10) unsigned NOT NULL,
		`create_by` int(10) unsigned NOT NULL,
		PRIMARY KEY (`id`)
	) ENGINE=InnoDB DEFAULT CHARSET=utf8;");

	$db->query("CREATE TABLE IF NOT EXISTS `update_file` (
		`path` varchar(255) NOT NULL,
		`package` varchar(200) NOT NULL,
		`version` int(10) unsigned NOT NULL,
		`hash` varchar(32) NULL,
		`content` LONGBLOB NULL,
		PRIMARY KEY (`path`)
	) ENGINE=InnoDB DEFAULT CHARSET=utf8;");

	$db->query("CREATE TABLE IF NOT EXISTS `update_migration` (
		`id` varchar(250) NOT NULL,
		`create_date` int(10) unsigned NOT NULL,
		`create_by` int(10) unsigned NOT NULL,
		PRIMARY KEY (`id`)
	) ENGINE=InnoDB DEFAULT CHARSET=utf8;");

	$db->query("CREATE TABLE IF NOT EXISTS `update_dependency` (
		`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
		`package` varchar(200) NOT NULL,
		`required` varchar(200) NOT NULL,
		`version` int(10) unsigned NOT NULL,
		PRIMARY KEY (`id`)
	) ENGINE=InnoDB DEFAULT CHARSET=utf8;");

	$db->query("CREATE TABLE IF NOT EXISTS `update_share` (
		`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
		`package` varchar(200) NOT NULL,
		`comment` varchar(200) NOT NULL,
		`pattern` varchar(200) NOT NULL,
		PRIMARY KEY (`id`)
	) ENGINE=InnoDB  DEFAULT CHARSET=utf8;");

	// Write Config files
	if( $_POST['use_ftp'] ) {
		$writer->put( 'inc/ftp.config.php', sprintf(
					"<?php\n\n\$ftp_host = '%s';\n\$ftp_user = '%s';\n\$ftp_pass = '%s';\n\$ftp_dir = '%s';\n",
					$_POST['ftp_host'], $_POST['ftp_user'], $_POST['ftp_pass'], $_POST['ftp_dir'] ));
	}

	$writer->put( 'inc/database.config.php', "<?php\n\n\$db = new sqlite_connection( 'db/system.sqlite' );\n\n");

	$db->update_server->insert($server);

	// Redirect
	header( 'LOCATION: '.IV_SELF );
	exit();
} catch( sqlite_exception $e ) {
	$error = $e->getError().$e->getSql();
} catch( Exception $e ) {
	$error = $e->getMessage();
}
